package com.clei.Y2023.M10.D30;

import com.clei.utils.ByteUtil;
import com.clei.utils.DateUtil;
import com.clei.utils.PrintUtil;

import java.time.LocalDateTime;

/**
 * 生成消防报警数据
 *
 * @author Y
 * @date 2023-10-30
 */
public class GenerateAlert {

    /**
     * 报警消息模版
     */
    private static final String TEMPLATE = "823830%s303B%s343C83";

    public static void main(String[] args) {
        // 单条测试 多条的话用个list在用代码处理下就行
        PrintUtil.log(getDataMsg("1-11-62", LocalDateTime.now()));
    }

    /**
     * @param id       id 格式为 number-number-number
     * @param dateTime dateTime 格式为 yyyy-Mm-dd HH:mm:ss
     * @return
     */
    private static String getDataMsg(String id, String dateTime) {
        LocalDateTime localDateTime = DateUtil.parse(dateTime);
        return getDataMsg(id, localDateTime);
    }

    /**
     * @param id       id 格式为 number-number-number
     * @param dateTime LocalDateTime
     * @return
     */
    private static String getDataMsg(String id, LocalDateTime dateTime) {
        return String.format(TEMPLATE, getId(id), getDateTime(dateTime));
    }

    /**
     * 获取id
     *
     * @param id id 格式为 number-number-number
     * @return hex
     */
    private static String getId(String id) {
        String[] arr = id.split("-");
        StringBuilder sb = new StringBuilder(12);
        for (int i = 0; i < 3; i++) {
            sb.append(num2Hex(Byte.parseByte(arr[i])));
        }
        return sb.toString();
    }

    /**
     * 获取时间
     *
     * @param date 日期
     * @return hex
     */
    private static String getDateTime(LocalDateTime date) {
        StringBuilder sb = new StringBuilder(24);
        sb.append(num2Hex((byte) date.getYear()));
        sb.append(num2Hex((byte) date.getMonthValue()));
        sb.append(num2Hex((byte) date.getDayOfMonth()));
        sb.append(num2Hex((byte) date.getHour()));
        sb.append(num2Hex((byte) date.getMinute()));
        sb.append(num2Hex((byte) date.getSecond()));
        return sb.toString();
    }

    /**
     * num -> hex
     *
     * @param b byte
     * @return hex 3X3X
     */
    private static String num2Hex(byte b) {
        String s = ByteUtil.toHex(b);
        char[] arr = s.toCharArray();
        return "3" + arr[0] + "3" + arr[1];
    }
}
